/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* fast = head, *del = head;
        ListNode* pre = nullptr;
        // 快指针先走n步
        while(n-- && fast != nullptr){
            fast = fast->next;
        }
        // 找到要删除节点del，和要删除节点前一节点pre    
        while(fast != nullptr){
            fast = fast->next;
            pre = del;
            del = del->next;
        }
               
        if(del == head){   // 如果删除的是头节点
            head = del->next;
        }
        else
            pre->next = del->next;
        delete del;

        return head;
    }
};